//
//  WorksViewController.m
//  Hand shadow
//
//  Created by A-01 on 2020/7/20.
//  Copyright © 2020 A-01. All rights reserved.
//

#import "WorksViewController.h"
#import "AppreciationCollectionViewCell.h"
#import "ZRImageBrower.h"

@interface WorksViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic, weak)UIButton * addButton;
@property (nonatomic, weak)UILabel * explainLab;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UIImageView * bottomImageView;
@property (nonatomic,strong)UIImagePickerController *imagePicker;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, weak)UILabel * noWorkLab;
@property (nonatomic, weak)UICollectionView * collectionView;
@property (nonatomic, strong)NSArray * dataList;

@end

@implementation WorksViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"Works";
    
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupUI{
    
    UIButton * addButton = [UIButton new];
    
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    [addButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    
    self.addButton = addButton;
    
    [self.view addSubview:self.addButton];
    
    
    UILabel * explainLab = [UILabel new];
    
    explainLab.text = @"After studying according to the works provided in “Basic Hand Shadow Learning”, you can try it at home. \nParents can record the children works while the children are playing hand shadows. Select a picture or take a photo by clicking on choose and add, on the left to enter the phone. Shown below are their works of the record.";
    explainLab.textColor = ZRBlackColor;
    explainLab.font = [UIFont boldSystemFontOfSize:15];
    explainLab.numberOfLines = 0;
    
    self.explainLab = explainLab;
    
    [self.view addSubview:self.explainLab];
    
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = [UIColor colorWithHexString:@"BDE0F9"];
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    
    UIImageView * bottomImageView = [UIImageView new];
    
    bottomImageView.image = [UIImage imageNamed:@"bottom_cat"];
    
    self.bottomImageView = bottomImageView;
    
    [self.view addSubview:self.bottomImageView];
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
            
    layout.itemSize =CGSizeMake(80, 80);
    layout.minimumLineSpacing = 10;
    //    layout.minimumInteritemSpacing = 20;
        //设置collectionView滚动方向
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
            //2.初始化collectionView
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(50, 35 , kScreenW - 240, 80) collectionViewLayout:layout];
            
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
            //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    //    [collectionView registerClass:[PictureCollectionViewCell class] forCellWithReuseIdentifier:@"PictureCollectionViewCell"];
    [collectionView registerNib:[UINib nibWithNibName:@"AppreciationCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WorksCollectionViewCell"];
            //4.设置代理
    collectionView.delegate = self;
    collectionView.dataSource = self;
        
    self.collectionView = collectionView;
        
    [self.bottomView addSubview:self.collectionView];
    
    
    UILabel * noWorkLab = [UILabel new];
    
    noWorkLab.text = @"No Work Yet";
    noWorkLab.font = [UIFont boldSystemFontOfSize:30];
    noWorkLab.textColor = [UIColor colorWithHexString:@"2C8FB4"];
    noWorkLab.textAlignment = NSTextAlignmentCenter;
    noWorkLab.hidden = YES;
    
    self.noWorkLab = noWorkLab;
    
    [self.bottomView addSubview:self.noWorkLab];
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"Choose photo style" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
           {
               //摄像头
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
           }else{

               UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                         message:@"You can not choose camera"
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                          
               UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                       handler:^(UIAlertAction * action) {
                                                                                           
                                                                                           
                          
                                                                                   }];
               [alert addAction:cancelAction];
               [self presentViewController:alert animated:YES completion:nil];
           }
       
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"album" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    AppreciationCollectionViewCell *cell = (AppreciationCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [ZRImageBrower showImage:cell.iconImageView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.dataList.count == 0) {
        
        self.noWorkLab.hidden = NO;
    }else{
        
        self.noWorkLab.hidden = YES;
    }
    return self.dataList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    AppreciationCollectionViewCell *cell = (AppreciationCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"WorksCollectionViewCell" forIndexPath:indexPath];
    
    NSData * imageData = self.dataList[indexPath.row];
    cell.iconImageView.image = [UIImage imageWithData:imageData];
    cell.tag = indexPath.row;
    
    UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];

    longPressRecognizer.minimumPressDuration = 0.8f; //触发长按事件时间为1.0秒
    longPressRecognizer.delegate = self;
    longPressRecognizer.view.tag = indexPath.row;
    [cell addGestureRecognizer:longPressRecognizer];

    return cell;
}


- (void)clickAddButton{
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}


#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; //通过key值获取到图片
    //给UIimageView赋值已经选择的相片
    NSData *imageData = UIImageJPEGRepresentation(image,0.5);
    NSArray * arr = DEF_GET_OBJECT(@"dataList");
    NSMutableArray * muArr= [NSMutableArray arrayWithArray:arr];
    [muArr addObject:imageData];
    DEF_SET_OBJECT(muArr, @"dataList");
    self.dataList = muArr.copy;
    
    [self.collectionView reloadData];
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {

        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Are you sure you want to delete this photo？"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * action) {
            AppreciationCollectionViewCell * superView = (AppreciationCollectionViewCell *)recognizer.view;
                                                                             NSMutableArray * muArr= [NSMutableArray arrayWithArray:self.dataList];
                                                                             [muArr removeObjectAtIndex:superView.tag]; //删除数据源
            
                                                                             DEF_SET_OBJECT(muArr, @"dataList");
                                                                             self.dataList = muArr.copy;
                                                                             [self.collectionView reloadData]; //刷新
            
                                                                         }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
                                                                                handler:^(UIAlertAction * action) {
                                                                                    
                                                                                    
                   
                                                                            }];
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else if (recognizer.state == UIGestureRecognizerStateEnded) {

        
    }
}


- (void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(65);
        make.top.mas_equalTo(self.backButton.mas_bottom).offset(30);
        make.width.height.mas_equalTo(80);
    }];
    
    [self.explainLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.addButton.mas_trailing).offset(30);
        make.trailing.mas_equalTo(self.view).offset(-50);
        make.top.mas_equalTo(self.addButton).offset(8);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(150);
    }];
    
    [self.bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-20);
        make.width.mas_equalTo(182);
        make.height.mas_equalTo(45);
    }];
    
    [self.noWorkLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(self.bottomView);
    }];
}


- (UIImagePickerController *)imagePicker{
    
    if (!_imagePicker) {
        
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _imagePicker.allowsEditing = YES;
    }
    
    return _imagePicker;
}

- (NSArray *)dataList{
    
    if (!_dataList) {
        
        _dataList = DEF_GET_OBJECT(@"dataList");
    }
    
    return _dataList;
}

@end
